import 'dart:developer';

import 'package:flutter_bloc/flutter_bloc.dart';

// 新的委托者
class SimpleBlocObserver extends BlocObserver {
  @override
  void onCreate(Cubit cubit) {
    log("SimpleBlocObserver onCreate");
  }

  @override
  void onClose(Cubit cubit) {
    log("SimpleBlocObserver onCreate");
  }

  @override
  void onError(Cubit cubit, Object error, StackTrace stackTrace) {
    log("SimpleBlocObserver onError");
  }

  @override
  void onTransition(Bloc bloc, Transition transition) {
    log("SimpleBlocObserver onTransition");
  }

  @override
  void onChange(Cubit cubit, Change change) {
    log("SimpleBlocObserver onChange");
  }

  @override
  void onEvent(Bloc bloc, Object event) {
    log("SimpleBlocObserver onEvent");
  }
}

void main() {
  Bloc.observer = SimpleBlocObserver();
  cubitMain();
  blocMain();
}

void cubitMain() {
  log("----------CUBIT----------");
  final cubit = CounterCubit();
  log("1>> ${cubit.state}");
  log("---------- cubit.increment ----------");
  cubit.increment();
  log("2>> ${cubit.state}");

  cubit.close();
}

void blocMain() async {
  log("----------BLOC----------");
  final bloc = CounterBloc();

  log("1> ${bloc.state}");
  log("---------- bloc 添加事件 ----------");
  bloc.add(CounterEvent.incremnt);

  await Future<void>.delayed(Duration.zero);

  log("2> ${bloc.state}");

  await bloc.close();
}

// Cubit实现
class CounterCubit extends Cubit<int> {
  CounterCubit() : super(0);

  void increment() {
    log("CounterCubit increment");
    return emit(state + 1);
  }
}

enum CounterEvent { incremnt }

// Bloc实现
class CounterBloc extends Bloc<CounterEvent, int> {
  CounterBloc() : super(0);

  @override
  Stream<int> mapEventToState(CounterEvent event) async* {
    log("CounterBloc mapEventToState");
    switch (event) {
      case CounterEvent.incremnt:
        log("CounterBloc mapEventToState CounterEvent.incremnt");
        yield state + 1;
        break;
    }
  }
}
